/**
 1.npm install mongodb --save-dev / cnpm install mongodb --save-dev

 2.var MongoClient = require('mongodb').MongoClient;

 var url = 'mongodb://localhost:27017/test';   连接数据库的地址

 3.连接数据库

 MongoClient.connect(url, function(err, db) {

});

 4.实现增加修改删除

 MongoClient.connect(url, function(err, db) {

    client.db('user').insertOne({'name':'zhangsan'},function(error,data){

    })

});
 */

const http = require('http');
const ejs = require('ejs');
const MongoClient = require('mongodb').MongoClient;
const DB_URL = 'mongodb://127.0.0.1:27017';
const app = require('./model/express-route');

/*async function db(dbName,callback){
    const client = new MongoClient(DB_URL);
    await client.connect(function (err) {
        if(err) throw err;
        const db = client.db(dbName);
        if(db) return db;
        throw '数据库获取失败';
    })
}*/

function db(dbName,callback){
    const client = new MongoClient(DB_URL,{useNewUrlParser: true, useUnifiedTopology:true});
    client.connect(function (err) {
        if(err) throw err;
        const db = client.db(dbName);
        callback(db,client);
    })
}

http.createServer(app).listen(3000);

app.get('/',function(req,res){
    db('test',function (db,client) {
        const collections = db.collection('user');
        collections.find({}).toArray(function (err,docs) {
            ejs.renderFile('views/index.ejs',{list:docs},function (err,data) {
                if(err){
                    client.close();
                    throw err;
                }else{
                    res.send(data);
                    client.close();
                }
            })
        })
    })
});


app.get('/add',(req,res)=>{
    MongoClient.connect(DB_URL,(err,client)=>{
        if(err) throw err;
        client.db('user').insertOne({name:'lisi',age:18},function (err,result) {
            if(err) throw err;
            res.send('增加数据成功');
            db.close();
        })
    })
});

app.get('/etail',(req,res)=>{
   MongoClient.connect(DB_URL,function (err,client) {
        if(err) throw err;
        client.db('user').updateOne({name:'lise'},{$set:{age:19}},function (err,result) {
            if(err) throw err;
            console.log(result);
            res.send('修改数据成功');
            db.close();
        })
   })
});

app.get('/delete',(req,res)=>{
   MongoClient.connect(DB_URL,function (err,client) {
        if(err) throw err;
        client.db('user').removeOne({age:19},function (err,result) {
            if(err) {
                res.send('删除失败');
                return false;
            }
            res.send('删除成功');
            db.close();
        })
   })
});